import axios from 'axios';
import React, { useEffect, useState } from 'react'
import { Table, Button, notification } from 'antd'

export default function Audit() {
  const [dataSource, setDataSource] = useState([]);
  const { roleId, region, username } = JSON.parse(localStorage.getItem("token"))
  useEffect(() => {
    const roleObj = {
      "1": "superadmin",
      "2": "admin",
      "3": "editor"
    }
    axios.get(`/news?auditState=1&_expand=category`).then(res => {
      const list = res.data
      // 登录对应用户只能看到自己所在区域的信息
      setDataSource(roleObj[roleId] === "superadmin" ? list : [
        ...list.filter(Item => Item.author === username),
        ...list.filter(Item => Item.region === region && roleObj
        [Item.reloId] === "editor")
      ])
    })

  }, [roleId, region, username])

  const columns = [
    {
      title: '新闻标题',
      dataIndex: 'title',
      key: 'name',  // 可写可不写
      render: (title, Item) => <a href={`#/news-manage/preview/${Item.id}`}>{title}</a>
    },
    {
      title: '作者',
      dataIndex: 'title',
    },
    {
      title: '新闻分类',
      dataIndex: 'category',
      render: (category) => <div>{category.title}</div>
    },
    {
      title: '操作',
      render: (Item) => <div>
        <Button type="primary" onClick={() => handleAudit(Item, 2, 1)}>通过</Button>
        <Button danger onClick={() => handleAudit(Item, 3, 0)}>驳回</Button>
      </div>
    },
  ];

  const handleAudit = (Item, auditState, publishState) => {
    // 把当前的哪一项驳回
    setDataSource(dataSource.filter(data => data.id !== Item.id))
    axios.get(`/news/${Item.id}`, {
      auditState,
      publishState
    }).then(res => {
      notification.info({
        message: `通知`,
        description: `您可以到【审核管理/审核列表】中查看你的新闻的审核状态`,
        placement: 'bottomRight',
      });
    })
  }

  return (
    <div>
      <Table
        columns={columns}
        dataSource={dataSource}
        pagination={{
          pageSize: 5
        }}
        rowKey={Item => Item.id}
      />
    </div>
  )
}
